//创建用户小仓库
import { defineStore } from "pinia";
//引入接口
import { login, logout, userInfo } from "@/api/user/index";
//引入数据类型
import type { UserState } from "@/store/modules/types/type";
import type { LoginInfo, LoginInfoResp, UserInfoResp } from "@/api/user/type";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import { constantsRoute } from "@/routers/routes";

//创建仓库
let useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN() || "",
      menuRoute: constantsRoute,
      username: "",
      avatar: "",
      usePermissions: [],
    };
  },
  //异步逻辑
  actions: {
    //登录
    async userLogin(data: LoginInfo) {
      let res: LoginInfoResp = await login(data);
      //登录成功：token
      //登录失败：展示错误信息
      if (res.code === 200) {
        //pinia存储一下token
        //由于pinia/vuex存储数据其实利用了js对象
        this.token = res.data as string;
        //本地持久化存储一份
        SET_TOKEN(res.data as string);
        //能保证返回一个成功的promise
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    //获取用户信息
    async userInfo() {
      let res: UserInfoResp = await userInfo();
      if (res.code === 200) {
        //用户信息
        this.username = res.data.name;
        this.avatar = res.data.avatar;
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    async userLogout() {
      let res: any = await logout();
      if (res.code === 200) {
        //清空仓库
        this.clear();
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    clear() {
      this.token = "";
      REMOVE_TOKEN();
      this.username = "";
      this.avatar = "";
    },
  },
  getters: {},
});

export default useUserStore;
